package com.sqx.modules.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.app.utils.UserConstantInterface;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.file.utils.Md5Utils;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.InvitationCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.api.SnsAPI;
import weixin.popular.util.JsonUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 用户
 *
 * @author fang
 * @date 2021/2/27
 */

@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private JwtUtils jwtUtils;
    private int number = 1;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private HelpTakeService takeService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private UserCertificationService certificationService;

    @Resource
    private UserCertificationDao userCertificationDao;

    /*
    * 获取所有的师傅信息
    * */
    @Override
    public Result getAllMaster() {
        // 师傅列表 userType为3 ，isAuthentication为1或3
        List<UserEntity> userEntityList = baseMapper.selectList(new QueryWrapper<UserEntity>().eq("user_type", 3).eq("is_authentication", 1).or().eq("is_authentication", 3));
        List<HashMap<String,Object>> data = new ArrayList<>();
        for (UserEntity userEntity : userEntityList) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("id",userEntity.getUserId());// 用户id
            // 经纬度
            item.put("latitude",userEntity.getLatitude());
            item.put("longitude",userEntity.getLongitude());
//            item.put("alpha",0); // 隐藏默认icon

//            // 文本内容
//            HashMap<String, Object> text = new HashMap<>();
//            text.put("borderWidth",1);
//            // 查询认证信息
//            UserCertification userCertification = userCertificationDao.selectOne(new LambdaQueryWrapper<UserCertification>().eq(UserCertification::getUserId, userEntity.getUserId()));
//            if(userCertification!=null){
//                text.put("content",userCertification.getName());// 设置师傅姓名
//            }
//            text.put("borderColor","#8DEEEE");
//            text.put("padding",20);
//            text.put("color","#FFFFFF");
//            text.put("bgColor","#8DEEEE");
//            text.put("borderRadius",100);
//            item.put("label",text);

            // 获取服务次数

            data.add(item);
        }
        return Result.success().put("data", data);
    }

    @Override
    public UserEntity queryByPhone(String phone) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
    }

    @Override
    public UserEntity queryByMasterOpenId(String masterOpenId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("master_open_id", masterOpenId));
    }

    @Override
    public UserEntity queryByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
    }

    @Override
    public UserEntity queryByShopOpenId(String shopOpenId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("shop_open_id", shopOpenId));
    }

    @Override
    public UserEntity queryByWxOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_open_id", openId));
    }

    @Override
    public UserEntity queryByAppleId(String appleId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("apple_id", appleId));
    }

    @Override
    public UserEntity queryByUserId(Long userId) {
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
        /*if(userEntity.getIsAuthentication()==null || userEntity.getIsAuthentication()!=1){
            UserCertification userCertification = userCertificationDao.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
            if(userCertification!=null && userCertification.getStatus()==1){
                userEntity.setIsAuthentication(1);
                baseMapper.updateById(userEntity);
            }
        }*/
        return userEntity;
    }

    @Override
    public UserEntity queryByInvitationCode(String invitationCode) {
        UserEntity user = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", invitationCode));
        if (user != null) {
            if (user.getRate() == null) {
                user.setRate(new BigDecimal(commonInfoService.findOne(206).getValue()));
                baseMapper.updateById(user);
            }
            if (user.getZhiRate() == null) {
                user.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue()));
                baseMapper.updateById(user);
            }
            if (user.getFeiRate() == null) {
                user.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue()));
                baseMapper.updateById(user);
            }

        }
        return user;
    }

    @Override
    public Result updatePhone(String phone, String msg, Long userId, Integer userType) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 != null) {
            if (userType == null) {
                userType = 1;
            }
            UserEntity userInfo = queryByPhone(phone);
            if (userInfo != null) {
                return Result.error("手机号已经被其他账号绑定");
            } else {
                UserEntity one = baseMapper.selectById(userId);
                one.setPhone(phone);
                baseMapper.updateById(one);
                return Result.success();
            }
        }
        return Result.error("验证码不正确");
    }

    @Override
    public Result iosRegister(String appleId) {
        if (StringUtils.isEmpty(appleId)) {
            return Result.error("账号信息获取失败，请退出重试！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserEntity userInfo = queryByAppleId(appleId);
        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
            //返回用户信息
            UserEntity user = queryByAppleId(appleId);
            return getResult(user);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }

    @Override
    public Result wxLogin(String code, Integer type) {
        try {
            String appid;
            String secret;
            if (type == null || type == 1) {
                //微信小程序APPID
                appid = commonInfoService.findOne(45).getValue();
                //微信小程序秘钥
                secret = commonInfoService.findOne(46).getValue();
            } else if (type == 2) {
                //微信小程序APPID
                appid = commonInfoService.findOne(239).getValue();
                //微信小程序秘钥
                secret = commonInfoService.findOne(240).getValue();
            } else {
                //师傅端微信小程序APPID
                appid = commonInfoService.findOne(303).getValue();
                //师傅端微信小程序秘钥
                secret = commonInfoService.findOne(304).getValue();
            }
            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", appid);
            param.put("secret", secret);
            param.put("js_code", code);
            param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE);
            param.put("scope", "snsapi_userinfo");
            // 发送请求
            String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param);
            log.info(wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();
            //返回微信小程序openId
            String open_id = jsonObject.get("openid").toString();
            Map<String, String> map = new HashMap<>();
            //判断是否注册过
            UserEntity userEntity = null;
            if (type == null || type == 1) {
                userEntity = queryByOpenId(open_id);
            } else if (type == 2) {
                userEntity = queryByShopOpenId(open_id);
            } else {
                userEntity = queryByMasterOpenId(open_id);
            }
            if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) {
                map.put("flag", "2");
            } else {
                map.put("flag", "1");
            }

            // 封装返回小程序
            map.put("session_key", session_key);
            map.put("open_id", open_id);
            if (jsonObject.get("unionid") != null) {
                String unionid = jsonObject.get("unionid").toString();
                map.put("unionid", unionid);
            } else {
                map.put("unionid", "-1");
            }


            return Result.success("登陆成功").put("data", map);
        } catch (Exception e) {
            System.err.println(e.toString());
            return Result.success("登录失败！");
        }
    }


    @Override
    public Result wxRegister(UserEntity userInfo1) {
        if(userInfo1.getType()==null){
            userInfo1.setType(1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserEntity userInfo = null;
        if (StringUtils.isNotEmpty(userInfo1.getOpenId())) {
            userInfo = queryByOpenId(userInfo1.getOpenId());
        } else if (StringUtils.isNotEmpty(userInfo1.getMasterOpenId())) {
            userInfo = queryByMasterOpenId(userInfo1.getMasterOpenId());
        } else {
            userInfo = queryByShopOpenId(userInfo1.getShopOpenId());
        }
        if (userInfo != null) {

            if (userInfo1.getType() == 3) {
                UserCertification certification = certificationService.getCertificationInfo(userInfo.getUserId());
                if (certification != null) {
                    if (certification.getClassify() == 2) {
                        return Result.error("账号已认证商家,无法登录师傅端");
                    }
                }
            }
            if (userInfo1.getType() == 2) {
                UserCertification certification = certificationService.getCertificationInfo(userInfo.getUserId());
                if (certification != null) {
                    if (certification.getClassify() == 1) {
                        return Result.error("账号已认证师傅,无法登录商家端");
                    }
                }
            }

            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                if (StringUtils.isBlank(userInfo.getPhone())) {
                    userInfo.setPhone(userInfo1.getPhone());
                }
            }
            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
        } else {
            //判断是否在app登陆过  手机号是否有账号
            UserEntity userByMobile = queryByPhone(userInfo1.getPhone());

            if (userByMobile!=null && userInfo1.getType() == 3) {
                UserCertification certification = certificationService.getCertificationInfo(userByMobile.getUserId());
                if (certification != null) {
                    if (certification.getClassify() == 2) {
                        return Result.error("账号已认证商家,无法登录师傅端");
                    }
                }
            }
            if (userByMobile!=null && userInfo1.getType() == 2) {
                UserCertification certification = certificationService.getCertificationInfo(userByMobile.getUserId());
                if (certification != null) {
                    if (certification.getClassify() == 1) {
                        return Result.error("账号已认证师傅,无法登录商家端");
                    }
                }
            }


            if (userByMobile != null) {
                if (userInfo1.getType() == 3) {
                    UserCertification certification = certificationService.getCertificationInfo(userByMobile.getUserId());
                    if (certification != null) {
                        if (certification.getClassify() == 2) {
                            return Result.error("账号已认证商家,无法登录师傅端");
                        }
                    }
                }
                if (userInfo1.getType() == 2) {
                    UserCertification certification = certificationService.getCertificationInfo(userByMobile.getUserId());
                    if (certification != null) {
                        if (certification.getClassify() == 1) {
                            return Result.error("账号已认证师傅,无法登录商家端");
                        }
                    }
                }
                //有账号则绑定账号
                userByMobile.setOpenId(userInfo1.getOpenId());
                userByMobile.setShopOpenId(userInfo1.getShopOpenId());
                userByMobile.setMasterOpenId(userInfo1.getMasterOpenId());
                baseMapper.updateById(userByMobile);
                if (userByMobile.getStatus().equals(2)) {
                    return Result.error("账号已被封禁，请联系客服处理！");
                }
            } else {
                if (StringUtils.isEmpty(userInfo1.getInviterCode())) {
                    userInfo1.setInviterCode(commonInfoService.findOne(3).getValue());
                }
                //没有则生成新账号
                userInfo1.setAvatar(commonInfoService.findOne(624).getValue());
                userInfo1.setCreateTime(date);
                userInfo1.setPlatform("小程序");
                userInfo1.setStatus(1);
                if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                    userInfo1.setUserName(userInfo1.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
                if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                    userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getPhone()));
                } else {
                    if (StringUtils.isNotEmpty(userInfo1.getOpenId())) {
                        userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getOpenId()));
                    } else if (StringUtils.isNotEmpty(userInfo1.getMasterOpenId())) {
                        userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getMasterOpenId()));
                    } else {
                        userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getShopOpenId()));
                    }
                }
                userInfo1.setUserType(userInfo1.getType());
                baseMapper.insertUser(userInfo1);
                userInfo1.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo1.getUserId()));
                baseMapper.updateById(userInfo1);
                //给用户创建钱包
                UserMoney userMoney = new UserMoney();
                userMoney.setUserId(userInfo1.getUserId());
                userMoney.setMoney(BigDecimal.ZERO);
                userMoney.setSafetyMoney(BigDecimal.ZERO);
                userMoneyDao.insert(userMoney);
                UserEntity userEntity = queryByInvitationCode(userInfo1.getInviterCode());
                if (userEntity != null) {
                    inviteService.saveBody(userInfo1.getUserId(), userEntity);
                }
            }
        }
        //返回用户信息
        UserEntity user;
        if (StringUtils.isNotEmpty(userInfo1.getOpenId())) {
            user = queryByOpenId(userInfo1.getOpenId());
        } else if (StringUtils.isNotEmpty(userInfo1.getMasterOpenId())) {
            user = queryByMasterOpenId(userInfo1.getMasterOpenId());
        } else {
            user = queryByShopOpenId(userInfo1.getShopOpenId());
        }
        return getResult(user);
    }


    @Override
    public Result wxBindMobile(String phone, String code, String wxOpenId, String token, String platform, Integer sysPhone, Integer userType) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getWxOpenId())) {
                return Result.error("当前手机号已经被其他微信绑定");
            }
            //小程序登陆过
            userInfo.setWxOpenId(wxOpenId);
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            baseMapper.updateById(userInfo);
        } else {
            //小程序没有登陆过
            userInfo = new UserEntity();
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            userInfo.setWxOpenId(wxOpenId);
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryByWxOpenId(userInfo.getWxOpenId());
        return getResult(userEntity);
    }

    @Override
    public Result iosBindMobile(String phone, String code, String appleId, String platform, Integer sysPhone, Integer userType) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        if (userType == null) {
            userType = 1;
        }
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getAppleId())) {
                return Result.error("当前手机号已经被其他苹果绑定");
            }
            userInfo.setAppleId(appleId);
            userInfo.setUpdateTime(simpleDateFormat.format(new Date()));
            baseMapper.updateById(userInfo);
        } else {
            userInfo = new UserEntity();
            userInfo.setSex(0);
            userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryByAppleId(userInfo.getAppleId());
        return getResult(userEntity);
    }


    @Override
    public Result wxAppLogin(String wxOpenId, String token) {
        UserEntity userEntity = queryByWxOpenId(wxOpenId);
        if (userEntity != null) {
            if (userEntity.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userEntity.setAvatar(user.getHeadimgurl());
                }
                userEntity.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userEntity.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userEntity.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userEntity);
            return getResult(userEntity);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }


    @Override
    public Result loginByOpenId(String openId) {
        UserEntity userEntity = queryByWxOpenId(openId);
        if (userEntity == null) {
            return Result.error(-200, "未注册！");
        }
        String token = jwtUtils.generateToken(userEntity.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", userEntity);
        return Result.success(map);
    }


    @Override
    public Result registerCode(String phone, String msg, String platform, Integer sysPhone, String openId, String inviterCode, Integer userType) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        //校验手机号是否存在
        if (userType == null) {
            userType = 1;
        }
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo!=null && userType == 3) {
            UserCertification certification = certificationService.getCertificationInfo(userInfo.getUserId());
            if (certification != null) {
                if (certification.getClassify() == 2) {
                    return Result.error("账号已认证商家,无法登录师傅端");
                }
            }
        }
        if (userInfo!=null && userType == 2) {
            UserCertification certification = certificationService.getCertificationInfo(userInfo.getUserId());
            if (certification != null) {
                if (certification.getClassify() == 1) {
                    return Result.error("账号已认证师傅,无法登录商家端");
                }
            }
        }
        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(StringUtils.isNotEmpty(openId)){
                userInfo.setWxOpenId(openId);
            }
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userInfo);
            return getResult(userInfo);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            userInfo.setPhone(phone);
            userInfo.setAvatar(commonInfoService.findOne(624).getValue());
            userInfo.setUserType(userType);
            userInfo.setInviterCode(inviterCode);
            userInfo.setPassword(DigestUtils.sha256Hex(phone));
            userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setWxOpenId(openId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.insertUser(userInfo);
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo.getUserId()));
            baseMapper.updateById(userInfo);
            msgDao.deleteById(msg1.getId());
            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.ZERO);
            userMoney.setSafetyMoney(BigDecimal.ZERO);
            userMoneyDao.insert(userMoney);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("恭喜您，账号注册成功！");
            messageInfo.setTitle("系统通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userInfo.getUserName());
            messageInfo.setUserId(String.valueOf(userInfo.getUserId()));
            messageInfo.setCreateAt(sdf.format(new Date()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
            UserEntity userEntity = queryByInvitationCode(userInfo.getInviterCode());
            if (userEntity != null) {
                inviteService.saveBody(userInfo.getUserId(), userEntity);
            }
            return getResult(userInfo);
        }
    }


    @Override
    public Result login(String phone, String pwd, Integer userType) {
        if (userType == null) {
            userType = 1;
        }
        UserEntity userEntity = queryByPhone(phone);
        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(pwd))) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);
    }


    @Override
    public Result getResult(UserEntity user) {
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", user);
        return Result.success(map);
    }

    @Override
    public Result sendMsg(String phone, String state, Integer userType) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println("sendMsg code is " + code);
        SmsSingleSenderResult result = null;
        /*if ("bindWx".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getWxOpenId())) {
                return Result.error("当前手机号已被其他微信账号绑定");
            }
        } else if ("bindIos".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getAppleId())) {
                return Result.error("当前手机号已被其他苹果账号绑定");
            }
        }*/
        if (userType == null) {
            userType = 1;
        }
        if (phone != null) {
            if ("forget".equals(state)) {
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone == null) {
                    return Result.error("手机号未注册");
                }
            } else if ("bingStaffUser".equals(state)) {
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone == null) {
                    return Result.error("手机号未注册");
                }
            }else if ("gzg".equals(state) || "assignTask".equals(state)) {
            } else {
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.error("当前手机号已被其他账号绑定");
                }
            }

        }
        CommonInfo three = commonInfoService.findOne(79);
        //默认使用腾讯云
        if (three == null || "1".equals(three.getValue())) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code, userType);
        } else if ("2".equals(three.getValue())) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, state, code);
        } else {
            return sendMsgDXB(phone, state, code, userType);
        }
    }


    @Override
    public Result sendMsg(String phone, String state, Integer code, Integer userType) {
        CommonInfo three = commonInfoService.findOne(79);
        if (userType == null) {
            userType = 1;
        }
        //默认使用腾讯云
        if (three == null || "1".equals(three.getValue())) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code, userType);
        } else if ("2".equals(three.getValue())) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, state, code);
        } else {
            return sendMsgDXB(phone, state, code, userType);
        }
    }


    private Result sendMsgAlibaba(String phone, String state, int code) {
        //阿里云短信accessKeyId
        CommonInfo three = commonInfoService.findOne(83);
        String accessKeyId = three.getValue();
        //阿里云短信accessSecret
        CommonInfo four = commonInfoService.findOne(84);
        String accessSecret = four.getValue();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonInfo name = commonInfoService.findOne(6);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", name.getValue());
        String value;
        switch (state) {
            case "register":
                value = commonInfoService.findOne(80).getValue();
                break;
            case "forget":
                value = commonInfoService.findOne(81).getValue();
                break;
            case "bind":
                value = commonInfoService.findOne(82).getValue();
                break;
            case "dx":
                value = commonInfoService.findOne(315).getValue();
                break;
            case "bingStaffUser":
                value = commonInfoService.findOne(314).getValue();
                break;
            case "assignTask":
                value = commonInfoService.findOne(316).getValue();
                break;
            default:
                value = commonInfoService.findOne(80).getValue();
                break;
        }

        request.putQueryParameter("TemplateCode", value);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String data = response.getData();
            JSONObject jsonObject = JSON.parseObject(data);
            if ("OK".equals(jsonObject.get("Code"))) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
           /*     UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }*/
                return Result.success("login");
            } else {
                if (jsonObject.get("Message").toString().contains("分钟")) {
                    return Result.error("短信发送过于频繁，请一分钟后再试！");
                } else if (jsonObject.get("Message").toString().contains("小时")) {
                    return Result.error("短信发送过于频繁，请一小时后再试！");
                } else if (jsonObject.get("Message").toString().contains("天")) {
                    return Result.error("短信发送过于频繁，请明天再试！");
                }
                log.info(jsonObject.get("Message").toString());
                return Result.error("短信发送失败！");
            }
        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    private Result sendMsgTencent(String phone, String state, int code, Integer userType) {
        SmsSingleSenderResult result = null;
        try {
            CommonInfo three = commonInfoService.findOne(31);
            String clientId = three.getValue();

            CommonInfo four = commonInfoService.findOne(32);
            String clientSecret = four.getValue();
            CommonInfo name = commonInfoService.findOne(6);
            /**
             * 发送短信验证码的状态、
             *
             * 在h5登录环境中 传的状态不是以下三种状态
             */
            SmsSingleSender ssender = new SmsSingleSender(Integer.valueOf(clientId), clientSecret);
            switch (state) {
                case "register":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "forget":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "bind":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "dx":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您有" + code + "条未读消息，赶快上线查看吧！", "", "");
                    break;
                case "bingStaffUser":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定公司操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "assignTask":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您有新的订单，请尽快上线查看并前往服务！", "", "");
                    break;
                default:
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
            }


            System.out.println(result);
            if (result.result == 0) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }
            } else {
                return Result.error(6, result.errMsg);
            }
        } catch (HTTPException | JSONException | IOException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    private Result sendMsgDXB(String phone, String state, int code, Integer userType) {
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        CommonInfo name = commonInfoService.findOne(6);
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        String value = "";
        switch (state) {
            case "register":
                value = "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "forget":
                value = "【" + name.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "bind":
                value = "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "dx":
                value = "【" + name.getValue() + "】您有" + code + "条未读消息，赶快上线查看吧！";
                break;
            case "bingStaffUser":
                value = "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定公司操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "assignTask":
                value = "【" + name.getValue() + "】您有新的订单，请尽快上线查看并前往服务！";
                break;
            default:
                value = "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
        }
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值：" + result);
        if ("0".equals(result)) {
            Msg byPhone = msgDao.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(code));
                byPhone.setPhone(phone);
                msgDao.updateById(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(code));
                msg.setPhone(phone);
                msgDao.insert(msg);
            }
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null) {
                return Result.success("login");
            } else {
                return Result.success("register");
            }
        } else {
//            return ResultUtil.error(6, result.errMsg);
            if ("30".equals(result)) {
                return Result.error("错误密码");
            } else if ("40".equals(result)) {
                return Result.error("账号不存在");
            } else if ("41".equals(result)) {
                return Result.error("余额不足");
            } else if ("43".equals(result)) {
                return Result.error("IP地址限制");
            } else if ("50".equals(result)) {
                return Result.error("内容含有敏感词");
            } else if ("51".equals(result)) {
                return Result.error("手机号码不正确");
            }
        }

        return Result.error("验证码发送失败");
    }


    @Override
    public Result getOpenId(String code, Long userId) {
        try {
            //微信appid
            CommonInfo one = commonInfoService.findOne(5);
            //微信秘钥
            CommonInfo two = commonInfoService.findOne(21);
            String openid = SnsAPI.oauth2AccessToken(one.getValue(), two.getValue(), code).getOpenid();
            if (StringUtils.isNotEmpty(openid)) {
                UserEntity userEntity = new UserEntity();
                userEntity.setUserId(userId);
                userEntity.setOpenId(openid);
                baseMapper.updateById(userEntity);
                return Result.success().put("data", openid);
            }
            return Result.error("获取失败");
        } catch (Exception e) {
            log.error("GET_OPENID_FAIL");
            return Result.error("获取失败,出错了！");
        }
    }

    @Override
    public UserEntity selectUserById(Long userId) {
        UserEntity userEntity = baseMapper.selectById(userId);
        if (userEntity != null) {
            UserVip userVip = userVipService.selectUserVipByUserId(userId);
            if (userVip != null) {
                if (userVip.getIsVip() != null && userVip.getIsVip() == 1) {
                    userEntity.setIsVip(1);
                    userEntity.setVipEndTime(userVip.getEndTime());
                }
            }
        }
        return userEntity;
    }


    @Override
    public Result selectUserPage(Integer page, Integer limit, String search, Integer sex, String platform, String sysPhone, Integer status, Long companyId, Integer isAuthentication, String userName, String phoneAndUserName, Integer isCompany, Integer shopType, String companyName, String invitationCode, String inviterCode, Integer isVip) {
        if (page == null || limit == null) {
            return Result.success().put("data", baseMapper.selectUserList(search, sex, platform, sysPhone, status, companyId, isAuthentication, userName, phoneAndUserName, isCompany, invitationCode, inviterCode, isVip));
        } else {
            Page<UserEntity> pages = new Page<>(page, limit);
            return Result.success().put("data", new PageUtils(baseMapper.selectUserPage(pages, search, sex, platform, sysPhone, status, companyId, isAuthentication, userName, phoneAndUserName, isCompany, shopType, companyName, invitationCode, inviterCode, isVip)));
        }
    }

    @Override
    public int queryInviterCount(String inviterCode) {
        return baseMapper.queryInviterCount(inviterCode);
    }

    @Override
    public int queryUserCount(int type, String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        if (date == null || date == "") {
            date = simpleDateFormat.format(new Date());
        }
        return baseMapper.queryUserCount(type, date);
    }

    @Override
    public Double queryPayMoney(int type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        String date = simpleDateFormat.format(new Date());
        return baseMapper.queryPayMoney(type, date);
    }

    @Override
    public IPage<Map<String, Object>> queryCourseOrder(Page<Map<String, Object>> iPage, int type, String date) {
        return baseMapper.queryCourseOrder(iPage, type, date);
    }

    @Override
    public int userMessage(String date, int type) {
        return baseMapper.userMessage(date, type);
    }

    @Override
    public int updateUserClientIdIsNull(String clientid) {
        return baseMapper.updateUserClientIdIsNull(clientid);
    }

    @Override
    public void pushToSingle(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("clientid", clientId));
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                if (userEntity != null) {
                    if (userEntity.getUserType() == 1) {
                        apiConfiguration.setAppId(commonInfoService.findOne(61).getValue());
                        apiConfiguration.setAppKey(commonInfoService.findOne(60).getValue());
                        apiConfiguration.setMasterSecret(commonInfoService.findOne(62).getValue());
                    } else if (userEntity.getUserType() == 2) {
                        apiConfiguration.setAppId(commonInfoService.findOne(264).getValue());
                        apiConfiguration.setAppKey(commonInfoService.findOne(263).getValue());
                        apiConfiguration.setMasterSecret(commonInfoService.findOne(265).getValue());
                    } else if (userEntity.getUserType() == 3) {
                        apiConfiguration.setAppId(commonInfoService.findOne(267).getValue());
                        apiConfiguration.setAppKey(commonInfoService.findOne(266).getValue());
                        apiConfiguration.setMasterSecret(commonInfoService.findOne(268).getValue());
                    }
                }

                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    GTNotification notification = new GTNotification();
                    pushDTO.setPushMessage(pushMessage);
                    // 配置通知栏图标
                    notification.setLogo(commonInfoService.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                    // 配置通知栏网络图标
                    notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png");
                    notification.setTitle(title);
                    notification.setBody(content);
                    notification.setClickType("startapp");
                    notification.setUrl(commonInfoService.findOne(19).getValue());
                    notification.setChannelLevel("3");
                    pushMessage.setNotification(notification);
                } else {
                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                }
                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.error("消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("消息推送成功失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }

    @Override
    public Result loginApp(String phone, String password, Integer userType) {
        //md5加密
        String pwd = DigestUtils.sha256Hex(password);
        if (userType == null) {
            userType = 1;
        }
        UserEntity userEntity = queryByPhone(phone);

        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (userType == 3) {
            UserCertification certification = certificationService.getCertificationInfo(userEntity.getUserId());
            if (certification != null) {
                if (certification.getClassify() == 2) {
                    return Result.error("账号已认证商家,无法登录师傅端");
                }
            }
        }
        if (userType == 2) {
            UserCertification certification = certificationService.getCertificationInfo(userEntity.getUserId());
            if (certification != null) {
                if (certification.getClassify() == 1) {
                    return Result.error("账号已认证师傅,无法登录商家端");
                }
            }
        }
        if (!userEntity.getPassword().equals(pwd)) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);

    }

    @Override
    public Result registApp(String userName, String phone, String password, String msg, String platform, String inviterCode, Integer userType) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        //校验手机号是否存在
        if (userType == null) {
            userType = 1;
        }
        if (userType == 3) {
            UserEntity entity = queryByPhone(phone);
            if (entity != null) {
                return Result.error("您已在用户端注册，请前往用户端登录！");
            }
        }
        UserEntity userInfo = queryByPhone(phone);

        if (userInfo != null) {
            return Result.error("手机号已经被注册！");
        } else {
            UserEntity userEntity = null;
            String value = commonInfoService.findOne(3).getValue();
            if (StringUtils.isBlank(inviterCode)) {
                inviterCode = value;
            } else {
                if (!inviterCode.equals(value)) {
                    userEntity = queryByInvitationCode(inviterCode);
                    if (userEntity == null) {
                        return Result.error("邀请码不正确");
                    }
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            userInfo.setUserType(userType);
            userInfo.setAvatar(commonInfoService.findOne(624).getValue());
            userInfo.setPhone(phone);
            userInfo.setUserName(userName);
            //对密码进行MD5加密
            userInfo.setPassword(DigestUtils.sha256Hex(password));
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setStatus(1);
            userInfo.setInviterCode(inviterCode);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setCreateTime(sdf.format(new Date()));
            baseMapper.insertUser(userInfo);
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo.getUserId()));
            //设置自己邀请码
            baseMapper.updateById(userInfo);
            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.ZERO);
            userMoney.setSafetyMoney(BigDecimal.ZERO);
            userMoneyDao.insert(userMoney);
            if (userEntity != null) {
                inviteService.saveBody(userInfo.getUserId(), userEntity);
            }
            return getResult(userInfo);
        }

    }


    @Override
    public Result forgetPwd(String pwd, String phone, String msg, Integer userType) {
        try {
            Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, msg);
            //校验短信验证码
            if (byPhoneAndCode == null) {
                return Result.error("验证码不正确");
            }
            if (userType == null) {
                userType = 1;
            }
            UserEntity userByPhone = queryByPhone(phone);
            userByPhone.setPassword(DigestUtils.sha256Hex(pwd));
            msgDao.deleteById(byPhoneAndCode.getId());
            baseMapper.updateById(userByPhone);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @Override
    public Result takingOrdersMessage(Page<Map<String, Object>> iPage, Long type, String date) {
        //接单分析
        return Result.success().put("data", new PageUtils(baseMapper.takingOrdersMessage(iPage, type, date)));
    }

    @Override
    public Result insertStaffUser(Long userId, String phone, String msg) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        UserEntity userEntity = queryByPhone(phone);
        if (userEntity.getCompanyId() != null && userEntity.getCompanyId() != 0) {
            return Result.error("该用户已绑定公司，请先退出后进行操作！");
        }
        userEntity.setCompanyId(userId);
        baseMapper.updateById(userEntity);
        return Result.success();
    }

    @Override
    public IPage<UserEntity> getWorkerUserList(Integer page, Integer limit, Long companyId, Integer sex, Integer workStatus, String phone, String userName) {
        Page<UserEntity> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }

        IPage<UserEntity> selectPage = baseMapper.getWorkerUserList(pages, companyId, sex, workStatus, phone, userName);
        for (UserEntity record : selectPage.getRecords()) {
            int orderCount = ordersService.count(new QueryWrapper<Orders>().eq("staff_user_id", record.getUserId()).in("state", 4, 1));
            int helpCount = takeService.count(new QueryWrapper<HelpTake>().eq("company_id", record.getUserId()).in("status", 1, 2));
            record.setOrderCount(orderCount + helpCount);
        }

        return selectPage;
    }

    @Override
    public Result cancelStaffUser(Long userId, String phone) {
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
        if (!userEntity.getCompanyId().equals(userId)) {
            return Result.error("当前用户不是你的员工");
        }
        return Result.upStatus(baseMapper.cancelStaffUser(phone));

    }

    @Override
    public Result insertAdminStaffUser(Long userId, String phone) {
        UserEntity staffUser = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
        staffUser.setCompanyId(userId);
        return Result.upStatus(baseMapper.updateById(staffUser));
    }

    @Override
    public Result giveUserVip(Long userId, Integer type, Integer day) {
        if (type == 2) {
            day = -day;
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        UserVip userVip;
        userVip = userVipService.getOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        if (userVip == null) {
            userVip = new UserVip();
            userVip.setVipNameType(3);
            userVip.setUserId(userId);
            userVip.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            userVip.setIsVip(1);
            LocalDateTime dateTime = LocalDateTime.now().plusDays(day);
            userVip.setEndTime(fmt.format(dateTime));
            userVipService.save(userVip);
        } else {
            //会员过期时间
            LocalDateTime parse = LocalDateTime.parse(userVip.getEndTime(), fmt);
            //如果已经过期,则从当前时间开始计算
            if (parse.isBefore(LocalDateTime.now())) {
                String endTime = fmt.format(LocalDateTime.now().plusDays(day));
                userVip.setEndTime(endTime);
            } else {
                //如果未过期,则从过期时间开始计算
                String endTime = fmt.format(LocalDateTime.parse(userVip.getEndTime(), fmt).plusDays(day));
                userVip.setEndTime(endTime);
            }
            userVip.setIsVip(1);
            userVipService.updateById(userVip);
        }
        return Result.success();
    }

    @Override
    public List<UserEntity> selectAuthUserList() {

        return baseMapper.selectAuthUserList();

    }
}
